package com.cgc.game.base;

public class MessageQueue {

	private int message_count_;
	private int max_messages_;
	private Message[] buffer_;
	
	//private static MessageQueue instance;
	private int in_ = 0, out_ = 0;
	
	/*public static MessageQueue getInstance(){
		if(instance == null){
			instance = new MessageQueue(10);
		}
		return instance;
	}*/
	
	public MessageQueue(int max_messages) {
		max_messages_   = max_messages;
		message_count_  = 0;
		buffer_          = new Message[max_messages_];
	}
	
	public synchronized boolean full () {	
		return full_i ();
	}
	
	public synchronized void put(byte mParam1, byte mParam2, Object msgBody){
		Message msgNew = new Message(mParam1, mParam2, msgBody);
		put(msgNew);
		msgNew = null;
	}
	
	public synchronized  void put(Message msg) {
		while (full_i ()) {
			try { 
//			    System.out.println("thread["+
//			      Thread.currentThread().getName()+
//			      "]"+
//			      "release monitor lock, wait for space in the queue");
                wait(); 
            } catch (InterruptedException e) {
                //do something.
            } finally{
                //do something.
            } 
		}//end while.
		
		put_i(msg);
		notifyAll();
	}
	
	public  Message get() {
		/*while (empty_i ()) {
	  		try { 
	  		    System.out.println("thread["+
	  		      Thread.currentThread().getName()+
	  		      "]"+
	  		      "release monitor lock, wait for message in the queue");
                			wait(); 
            } catch (InterruptedException e) {
            //do something.
            } finally { 
                //do something.
            } 
		}//end while.*/
		if(empty_i())
			return null;
		
		Message m = get_i ();
		//notifyAll();
		return m;
	}
	
	private boolean empty_i () {
		return message_count_ == 0;
	}
	
	private boolean full_i () {
		return message_count_ == max_messages_;
	}
	
	private void put_i (Message msg) {
	    //System.out.println("thread ["+
	    //    Thread.currentThread().getName()+
	    //    "] put message <"+ msg.toString() + ">" +
	    //    "to the queue, in_=" + in_);
		buffer_[in_] = msg; 
        in_ = (in_ + 1) % max_messages_;  
        message_count_++; 
        //System.out.println("in_=" + in_ + "message_cout=" + message_count_);
	}
	
	private Message get_i() {
		//System.out.println("out=" + out_);
        Message msg = buffer_[out_]; 
        buffer_[out_] = null;
            out_= (out_ + 1) % max_messages_;
            message_count_--;
//            if(!Const.isIPTV){
//            	System.out.println("thread ["+
//            		Thread.currentThread().getName()+
//            		"] get message <" + msg.toString() + ">" +
//            	    "from the queue out_=" + out_);
//            }
            if(msg == null)
            {
            	//System.out.println("error");
            }
	    return msg;
	}
}
